package com.nrgedge.recaptcha.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import net.tanesha.recaptcha.ReCaptchaException;
import net.tanesha.recaptcha.http.HttpLoader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

public class HttpClientProxyHttpLoader implements HttpLoader {
	
	private HttpClient client; 
	
	public HttpClientProxyHttpLoader(String proxyHost, int proxyPort) {
		this(proxyHost, proxyPort, null, null);
	}
	
	public HttpClientProxyHttpLoader(String proxyHost, int proxyPort, String username, String password) {
		this.client = new HttpClient();
		this.client.getParams().setParameter("http.socket.timeout", new Integer(10000));
		
		this.client.getHostConfiguration().setProxy(proxyHost, proxyPort);
		
		if (username != null && username.trim().length() > 0) {
			this.client.getParams().setAuthenticationPreemptive(true);	
			this.client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
		}
	}
	
	public String httpGet(String urlS) {
		final HttpMethod method = new GetMethod(urlS);
		
		try {
			client.executeMethod(method);
			return method.getResponseBodyAsString();
		} catch (HttpException e) {
			throw new ReCaptchaException("Cannot load URL: " + e.getMessage(), e);
		} catch (IOException e) {
			throw new ReCaptchaException("Cannot load URL: " + e.getMessage(), e);
		} finally {
			method.releaseConnection();
		}
	}

	public String httpPost(String urlS, String postdata) {
		final PostMethod method = new PostMethod(urlS);
		
		try {
			method.setRequestEntity(new StringRequestEntity(postdata, "application/x-www-form-urlencoded", "UTF-8"));
			client.executeMethod(method);
			return method.getResponseBodyAsString();
		} catch (UnsupportedEncodingException e) {
			throw new ReCaptchaException("Cannot load URL: " + e.getMessage(), e);
		} catch (HttpException e) {
			throw new ReCaptchaException("Cannot load URL: " + e.getMessage(), e);
		} catch (IOException e) {
			throw new ReCaptchaException("Cannot load URL: " + e.getMessage(), e);
		} finally {
			method.releaseConnection();
		}

	}

	public HttpClient getClient() {
		return client;
	}

	public void setClient(HttpClient client) {
		this.client = client;
	}
	
}
